<?php

namespace App\Http\Controllers\Adminer;

use App\Exceptions\BaseException;
use App\Http\Controllers\AdminController;
use App\Models\Purview;
use App\Models\Role;
use App\Services\PurviewService;
use App\Services\TreeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
class RoleController extends AdminController
{
    protected $data;
    function __construct()
    {
        parent::__construct();
        $this->data['title'] = $this->base['controller'].$this->base['action'];
        $this->data['title_en'] = "Role";
        $this->data['title_url'] = route("role.index");
        $this->data['is_search'] = FALSE;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $rolearr = Role::orderBY('lft','asc')->get()->toArray();
        $status_names = Role::$status_names;
        $html = "";
        if(!empty($rolearr)){
            foreach($rolearr as $key=>$view){
                $rolearr[$key]['status_name'] = $status_names[$view['status']];
            }
            $ext_html = 'role';
            $html .= (new TreeService())->getList($rolearr,TRUE,'role',$ext_html);
        }
        $this->data['html'] = $html;
        return view("adminer.role.index",$this->data);
    }

    public function sort(Request $request){
        $data = $request->post('data');
        if(strpos($data,"children")){
            throw new BaseException('只允许同级排序');
        }
        $sorts = json_decode($data,true);
        if(is_array($sorts)){
            //dd($sorts);
            $this->_sort(0,$sorts);
        }else{
            throw new BaseException('数据出错');
        }
    }
    private function _sort($parent,$children){
        foreach($children as $c=>$child){
            $lft = $c;
            $new_parent = $child['id'] ?? 0;
            if($new_parent == 0){
                return false;
            }
            // 执行修改
            $payload['lft'] = $lft;
            Role::where('id',$new_parent)->update($payload);
            $new_chilren = $child['children'] ?? [];
            if(count($new_chilren) > 0){
                $this->_sort($new_parent,$new_chilren);
            }
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view("adminer.role.create",$this->data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $info=$request->only(['title','description','status']);
        // 验证不为空
        Validator::make($info, [
            'title' => ['bail','required',Rule::unique('role'),],
            'description' => ['bail','required'],
        ],[
            'title.required'       => '请输入角色名称',
            'description.required'       => '请输入角色描述',
            'title.unique'         => '角色名称已使用',
        ])->validate();
        $data = new Role($info);
        if(!$data->save()){
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"新增角色失败");
            throw new BaseException('保存失败');
        }
        AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"新增角色-".$info['title']);
        return $this->successResponse('保存成功',[],200,route("role.index"));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $info = Role::find($id);
        if(!$info){
            throw new BaseException('数据不存在');
        }else{
            return $this->successResponse('',$info->toArray(),200,'');
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $info = Role::find($id);
        if($info){
            $this->data['info'] = $info;
            return view("adminer.role.edit",$this->data);
        }else{
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],$id,"数据错误");
            return response()->json([
                'code'      => 422001,
                'message'   => "数据错误",
            ]);
        }

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $info = Role::find($id);
        if($info){
            $payload=$request->only(['title','description','status']);
            // 验证不为空
            Validator::make($payload, [
                'title' => ['bail','required',Rule::unique('role')->ignore($id)],
                'description' => ['bail','required'],
            ],[
                'title.required'       => '请输入角色名称',
                'description.required'       => '请输入角色描述',
                'title.unique'         => '角色名称已使用',
            ])->validate();
            if(!Role::where('id',$id)->update($payload)){
                AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"修改角色失败");
                throw new BaseException('保存失败');
            }
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"修改角色-".$payload['title']);
            return $this->successResponse('保存成功',[],200,route("role.index"));
        }else{
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],$id,"数据错误");
            return response()->json([
                'code'      => 422001,
                'message'   => "数据错误",
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(!Role::destroy($id)){
            throw new BaseException('操作失败');
        }

        return $this->successResponse('操作成功');
    }

    /**
     * 权限分配
     */
    public function assign($id,Request $request)
    {
        $view = Role::find($id)->toArray();
        if ($view) {
            $purview = unserialize($view['purviewpids']);
            $allpurview = Purview::where('status',Purview::STATUS_SUCCESS)->orderBy('lft','asc')->get()->toArray();
            $purviewstr = '';
            if ($allpurview) {
                $newarr = array();
                foreach ($allpurview as $item) {
                    $newarr[$item['parent']][$item['id']] = $item;
                }
                $arr = array();
                $purview_list = trans('content');
                foreach ($newarr[0] as $item) {
                    $check = !empty($purview[$item['pid']]) ? "checked" : "";
                    //dd($check);
                    $purviewstr .= '<li><a tname="purview[]" tvalue="' . $item['id'] . '" ' .$check. '>' . $item['title'] . '</a>';

                    $purviewstr .= $this->_formatPurview($newarr, $purview, $item['id'], $purview_list);
                    $purviewstr .= '</li>';
                }
            }
            //echo $purviewstr;exit;
            unset($allpurview, $purview, $newarr);
            $this->data['info'] = $view;
            $this->data['purviewstr'] = $purviewstr;
            return view("adminer.role.assign",$this->data);
        }else{
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],$id,"数据错误");
            return response()->json([
                'code'      => 422001,
                'message'   => "数据错误",
            ]);
        }
    }

    private static function _formatPurview(&$newarr, &$purview, $parentid, $purview_list)
    {
        $purviewstr = '';
        if (isset($newarr[$parentid])) {
            $purviewstr .= '<ul>';
            foreach ($newarr[$parentid] as $key=>$item) {
                $purviewstr .= '<li><a tname="purview[]" tvalue="' . $item['id'] . '" ' . (!empty($purview[$item['pid']]) ? 'checked' : '') . '>' . $item['title'] . '</a>';
                $flag = "";
                //if()
                //$purviewstr .= "d.add(".$item['id'] .",".$item['parent'].",'".$item['pid']."','".$item['id']."','".$item['title']." ');";
                if ($item['func'] != '') {
                    $funcarr = explode(',', $item['func']);
                    $purviewstr .= '<ul class="treefunc">';
                    foreach ($funcarr as $f=>$funcitem) {
                        $purviewstr .= '<li><a tname="func_' . $item['id'] . '[]" tvalue="' . $funcitem . '"  ' . (!empty($purview[$item['pid']]) && in_array($funcitem, $purview[$item['pid']]) ? 'checked' : '') . '>' . $purview_list[$funcitem] . '</a></li>';
                        //$fun_name = trans("content.".$funcitem);
                        //$purviewstr .= "d.add(".$item['id']."999".$f.",".$item['id'].",'','func_".$funcitem."','".$fun_name."');";
                    }
                    $purviewstr .= '</ul>';
                }
                $purviewstr .= self::_formatPurview($newarr, $purview, $item['id'],$purview_list);
                $purviewstr .= '</li>';
            }
            $purviewstr .= '</ul>';
        }
        return $purviewstr;
    }

    /**
     * 权限分配保存
     * @param $id
     * @param Request $request
     */
    public function assign_do($id,Request $request){
        $info = Role::find($id);
        if($info){
            $purview = $request->post('purview');
            // 处理传递过来的不包含最高级的问题
            $parents = [];
            foreach($purview as $child){
                $self = Purview::find($child);
                $purview[] = $self->parent;
            }
            $purview = array_unique($purview);
//            echo implode(",",$purview);
//            dd($purview);
            $allpurview = PurviewService::purviewAllByOpt(Purview::STATUS_SUCCESS,"",implode(",",$purview))->toArray();
            $purviewids = array();
            $purviewpids = array();
            foreach ($allpurview as $item) {
                $purviewids[] = $item['id'];
                //$purviewpids[$item['pid']] = isset($post['func_' . $item['id']]) ? $post['func_' . $item['id']] : array();
                $purviewpids[$item['pid']] = $request->post('func_' . $item['id']) ?? array();
            }
            if(!empty($purviewids)){
                foreach($purviewids as $pur){
                    $self = Purview::find($pur);
                    $purviewids[] = $self->parent;
                }
            }
            $purviewids = array_unique($purviewids);
            $info->purviewids = implode(',', $purviewids);
            $info->purviewpids = serialize($purviewpids);
            if(!$info->save()){
                AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"权限分配失败");
                throw new BaseException('保存失败');
            }
            dd($_SERVER["QUERY_STRING"]);
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"权限分配-".$info->title);
            return $this->successResponse('保存成功',[],200,route("role.index"));
        }else{
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],$id,"数据错误");
            return response()->json([
                'code'      => 422001,
                'message'   => "数据错误",
            ]);
        }
    }
}
